package com.mlnx.netty.ecg.handler;

import com.mlnx.common.utils.MyLog;
import com.mlnx.device.session.SessionManagerFactory;
import com.mlnx.device.session.core.DeviceSession;
import com.mlnx.device.session.manager.MutilDeviceSessionManager;
import com.mlnx.mptp.PacketType;
import com.mlnx.mptp.ResponseCode;
import com.mlnx.mptp.mptp.MpPacket;
import com.mlnx.mptp.mptp.body.Body;
import com.mlnx.mptp.mptp.head.Header;
import com.mlnx.netty.base.message.RegisterMessage;
import com.mlnx.tp.base.model.DeviceType;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

/**
 * 设备是否注册验证
 *
 * @author Administrator
 */
public class MpVerify extends SimpleChannelInboundHandler<MpPacket> {

    MyLog log = MyLog.getLog(getClass());

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, MpPacket mpPacket) throws Exception {

        MutilDeviceSessionManager sessionManager = SessionManagerFactory.getInstance().getMutilDeviceSessionManager();

        Header header = mpPacket.getHeader();
        Body body = mpPacket.getBody();

        String deviceID = body.getDeviceId();

        DeviceSession session = (DeviceSession) sessionManager.getSession(ctx.channel());

        if (session != null) {
            sessionManager.refreshLastTime(ctx.channel());
        }

        // 不是注册命令
        if (mpPacket.getHeader().getPacketType().compareTo(PacketType.REGISTER) != 0) {

            if (session != null) {
                ctx.fireChannelRead(mpPacket);
            } else {
                log.error("{} 设备未注册 ：{}", header.getDeviceType().toString(), deviceID);
                MpPacket packet = new MpPacket().pushAck(DeviceType.SERVER, body.getMessageId(),
                        ResponseCode.NOT_REGISTER);
                ctx.channel().writeAndFlush(packet);
            }
        } else {

            // 已经注册
            if (session != null) {
                boolean closeChannel = !ctx.channel().equals(session.getChannel());
                sessionManager.removeSession(session.getChannel());
            }
            RegisterMessage registerMessage = new RegisterMessage();
            registerMessage.setDeviceId(body.getDeviceId());
            registerMessage.setDeviceType(header.getDeviceType());

            registerMessage.setUsrName(body.getName());
            registerMessage.setPassword(body.getPassWord());

            ctx.fireChannelRead(registerMessage);
        }

    }

}
